package com.example.badyloans.controller;

import com.example.badyloans.common.ReturnResult;
import com.example.badyloans.pojo.*;
import com.example.badyloans.servlet.TAccountFlowService;
import com.example.badyloans.servlet.TBankCardService;
import com.example.badyloans.servlet.TRechargeService;
import com.example.badyloans.servlet.TUserWalletService;
import com.example.badyloans.util.PageSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Random;
import java.util.UUID;

/**
 * @author 啊桥哦
 * @Description: 银行卡表的操作
 * @date 2020-07-15 14:25
 */
@RestController
public class UserTBankCardController {
    private static  final Logger log= LoggerFactory.getLogger(UserTBankCardController.class);
    @Resource
    private TBankCardService tBankCardService;
    @Resource
    private TRechargeService tRechargeService;
    @Resource
    private TUserWalletService tUserWalletService;
    @Resource
    private TAccountFlowService tAccountFlowService;

    /**
     * 查询银行卡是否绑定
     * @param id
     * @return
     */
    @PostMapping("user/bankcard/get/{id}")
    public ReturnResult bankcardget(@PathVariable String id){
        TBankCard tBankCard = new TBankCard();
        if (StringUtils.isEmpty(id)) {
            return ReturnResult.fail("参数不能为空");
        }
        tBankCard=tBankCardService.selectByPrimaryKey(id);
        if (tBankCard!=null) {
            return ReturnResult.success(tBankCard,null);
        }
        return ReturnResult.fail("404","没有绑定银行卡");
    }

    /**
     * 绑定银行卡
     */
    @PostMapping("/user/bankcard/add")
    public ReturnResult bankcardadd(TBankCard tBankCard){
        TBankCard tBankCard1=tBankCardService.selectByPrimaryKey(tBankCard.getId());
        if(tBankCard1==null){
            String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
            tBankCard.setId(uuid);
            tBankCard.setBalance(10000*100L);
            int count=tBankCardService.insertSelective(tBankCard);
            if(count>0){
                return ReturnResult.succes();
            }else {
                return ReturnResult.fail("绑定失败");
            }
        }else{
            String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
            tBankCard.setId(uuid);
            int count=tBankCardService.insertSelective(tBankCard);
            if(count>0){
                return ReturnResult.succes();
            }else {
                return ReturnResult.fail("绑定失败");
            }
        }
    }

    /**
     * 充值银行卡余额  等审核用过在进行追加金额*
     * @return
     */
    @PostMapping("system/recharge/add")
    public ReturnResult rechargeaddinsert(TBankCard tBankCard,TRecharge tRecharge,HttpServletRequest request){
        tBankCard=tBankCardService.selectByPrimaryKey(tBankCard.getUserId());
        TUserWallet tUserWallet=tUserWalletService.selectByPrimaryKey(tBankCard.getUserId());
        if(tBankCard==null){
            return ReturnResult.fail("必须绑定银行卡才能进行充值");
        }else{
            String money=request.getParameter("showAmount");
            Long money1=null;
            if(money!=null){
                money1=Long.valueOf(money);
            }
            //判断金额是否小于或者等于银行卡余额
            if(money1<=tBankCard.getBalance() && money1>0){
                Long a=tBankCard.getBalance()-money1*100L;
                /*TUserWallet tUserWallet=tUserWalletService.selectByPrimaryKey(tBankCard.getUserId());
                tUserWallet.setAvailableAmount(tUserWallet.getAvailableAmount()+money1*100L);
                int twal=tUserWalletService.updateByPrimaryKeySelective(tUserWallet);*/
                tBankCard.setBalance(a);
                int count=tBankCardService.updateByPrimaryKeySelective(tBankCard);
                if(count>0){
                    tRecharge.setId(UUID.randomUUID().toString().replace("-", "").toLowerCase());
                    tRecharge.setUserId(tBankCard.getUserId());
                    tRecharge.setBankCardId(tBankCard.getCardNumber());
                    Long tradeNo= System.currentTimeMillis()+Math.abs(new Random().nextInt());
                    String trade=null;
                    if (tradeNo!=null){
                        trade=tradeNo.toString();
                    }
                    tRecharge.setTradeNo(trade);
                    tRecharge.setRechargeTime(LocalDateTime.now());
                    tRecharge.setState(1);
                    tRecharge.setCreateTime(LocalDateTime.now());
                    int sum=tRechargeService.insertSelective(tRecharge);
                    if(sum>0){
                        TAccountFlow tAccountFlow = new TAccountFlow();
                        Long tradeNo1= System.currentTimeMillis()+Math.abs(new Random().nextInt());
                        tAccountFlow.setId(tradeNo1);
                        tAccountFlow.setAccountId(tRecharge.getUserId());
                        tAccountFlow.setAmount(tRecharge.getAmount());
                        tAccountFlow.setFlowType(50);
                        tAccountFlow.setAvailableAmount(tUserWallet.getAvailableAmount());
                        tAccountFlow.setFreezeAmount(tUserWallet.getFreezeAmount());
                        tAccountFlow.setRemark("充值成功，充值金额："+tRecharge.getAmount()*0.01+"元");
                        tAccountFlow.setCreateTime(LocalDateTime.now());
                        int count1=tAccountFlowService.insertSelective(tAccountFlow);
                        if(count1>0){
                            return ReturnResult.succes();
                        }else{
                            return ReturnResult.fail("流水记录失败");
                        }
                    }else {
                        return ReturnResult.fail("充值失败");
                    }
                }else{
                    return ReturnResult.fail("充值失败");
                }
            }else{
                return ReturnResult.fail("充值失败，余额不足，或者金额不对");
            }

        }
    }

    /**
     * 查询充值记录
     * @return
     */
    @PostMapping("system/recharge/query")
    public ReturnResult rechargequery(loadrecharge loadrecharge){
        PageSupport page=new PageSupport();
        page.setPageSize(5);
        page.setTotalCount(tRechargeService.selectBy(loadrecharge.getUserId(),loadrecharge.getState(),loadrecharge.getBeginDate(),loadrecharge.getEndDate())); //查询总记录数
        page.setCurrentPageNo(loadrecharge.getCurrentPage());
        Integer pageSize=page.getPageSize();       //拿到页大小
        Integer currentPageNo=page.getCurrentPageNo(); //拿到页码
        List<TRecharge> list=tRechargeService.selecttrecharge(loadrecharge.getUserId(),((currentPageNo-1)*pageSize),pageSize,loadrecharge.getBeginDate(),loadrecharge.getEndDate(),loadrecharge.getState());
        if (list==null){
            return  ReturnResult.fail("没有数据");
        }
        return ReturnResult.success(list,page);
    }

    /**
     * 充值审核
     * @return
     */
    @PostMapping("system/recharge/audit")
    public ReturnResult rechargeaudit(@RequestParam(required = false) Integer state,@RequestParam(required = false) String id){
        //根据id查询出充值的记录，
        TRecharge tRecharge=tRechargeService.selectByPrimaryKey(id);
        String ids=null;
        //提现是把余额的钱提到银行卡   充值是把银行卡的钱充值到余额
        //点击审核通过时判断是否是2  是就进行余额追加
        if(state.equals(2)){
            //拿到充值的金额
            Long mount=tRecharge.getAmount();
            log.info(String.valueOf(mount));
            System.out.println(mount);
            //拿到充值的金额写到用户余额里面去
            ids=tRecharge.getUserId();
            TUserWallet tUserWallet =tUserWalletService.selectByPrimaryKey(ids);
            tUserWallet.setAvailableAmount(tUserWallet.getAvailableAmount()+mount);
            //审核通过时进行账户余额增加
            int count=tUserWalletService.updateByPrimaryKeySelective(tUserWallet);
            if(count>0){
                int coun=tRechargeService.update(state, id);
                if(coun>0){
                    return  ReturnResult.succes();
                }else{
                    return ReturnResult.fail("修改状态失败");
                }
            }else{
                return ReturnResult.fail("充值失败");
            }
        }else if(state.equals(0)){
            //else为审核拒绝
            //审核不通过时进行把充值的钱退回银行卡
            //拿到充值的金额
            Long mount=tRecharge.getAmount();
            log.info(String.valueOf(mount));
            TBankCard tBankCard =tBankCardService.selectByPrimaryKey(null);
            //拿到充值的金额写到用户银行卡里面去
            tBankCard.setBalance(tBankCard.getBalance()+mount);
            int count=tBankCardService.updateByPrimaryKeySelective(tBankCard);
            if(count>0){
                int coun=tRechargeService.update(state, id);
                if(coun>0){
                    return  ReturnResult.succes();
                }else{
                    return ReturnResult.fail("修改状态失败");
                }
            }
        }
        return ReturnResult.fail("充值失败");
    }
}
